package com.example.blog.modules.system.controller;

import com.example.blog.common.api.ApiResponse;
import com.example.blog.common.security.HasPermission;
import com.example.blog.modules.system.dto.DashboardDTO;
import com.example.blog.modules.system.dto.DateRangeRequest;
import com.example.blog.modules.system.service.DashboardService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Tag(name = "仪表盘", description = "仪表盘相关接口")
@RestController
@RequestMapping("/api/dashboard")
@RequiredArgsConstructor
@Validated
public class DashboardController {

    private final DashboardService dashboardService;
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

    @Operation(summary = "获取仪表盘数据")
    @GetMapping
    @HasPermission("dashboard:view")
    public ApiResponse<DashboardDTO> getDashboardData(@Valid DateRangeRequest dateRange) {
        return ApiResponse.success(dashboardService.getDashboardData(
            dateRange.getStartDate(),
            dateRange.getEndDate()
        ));
    }

    @Operation(summary = "导出仪表盘数据")
    @GetMapping("/export")
    @HasPermission("dashboard:export")
    public ResponseEntity<Resource> exportDashboardData(
            @Valid DateRangeRequest dateRange,
            @RequestParam(defaultValue = "excel") String format) {
        
        Resource resource = dashboardService.exportDashboardData(
            dateRange.getStartDate(),
            dateRange.getEndDate(),
            format
        );

        String filename = String.format("dashboard_%s_%s.%s",
            dateRange.getStartDate().format(DATE_FORMATTER),
            dateRange.getEndDate().format(DATE_FORMATTER),
            getFileExtension(format));

        return ResponseEntity.ok()
            .contentType(getMediaType(format))
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
            .body(resource);
    }

    @Operation(summary = "获取趋势数据")
    @GetMapping("/trends")
    @HasPermission("dashboard:view")
    public ApiResponse<DashboardDTO> getTrendData(
            @RequestParam(defaultValue = "7") int days,
            @RequestParam(required = false) LocalDate startDate) {
        return ApiResponse.success(dashboardService.getTrendData(days, startDate));
    }

    @Operation(summary = "导出趋势数据")
    @GetMapping("/trends/export")
    @HasPermission("dashboard:export")
    public ResponseEntity<Resource> exportTrendData(
            @RequestParam(defaultValue = "7") int days,
            @RequestParam(required = false) LocalDate startDate,
            @RequestParam(defaultValue = "excel") String format) {
        
        Resource resource = dashboardService.exportTrendData(days, startDate, format);
        String filename = String.format("trends_%d_days.%s", days, getFileExtension(format));

        return ResponseEntity.ok()
            .contentType(getMediaType(format))
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
            .body(resource);
    }

    @Operation(summary = "获取热门分类")
    @GetMapping("/categories/top")
    @HasPermission("dashboard:view")
    public ApiResponse<DashboardDTO> getTopCategories(
            @RequestParam(defaultValue = "10") int limit) {
        return ApiResponse.success(dashboardService.getTopCategories(limit));
    }

    @Operation(summary = "导出热门分类")
    @GetMapping("/categories/top/export")
    @HasPermission("dashboard:export")
    public ResponseEntity<Resource> exportTopCategories(
            @RequestParam(defaultValue = "10") int limit,
            @RequestParam(defaultValue = "excel") String format) {
        
        Resource resource = dashboardService.exportTopCategories(limit, format);
        String filename = String.format("top_categories_%d.%s", limit, getFileExtension(format));

        return ResponseEntity.ok()
            .contentType(getMediaType(format))
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
            .body(resource);
    }

    @Operation(summary = "获取热门标签")
    @GetMapping("/tags/top")
    @HasPermission("dashboard:view")
    public ApiResponse<DashboardDTO> getTopTags(
            @RequestParam(defaultValue = "10") int limit) {
        return ApiResponse.success(dashboardService.getTopTags(limit));
    }

    @Operation(summary = "导出热门标签")
    @GetMapping("/tags/top/export")
    @HasPermission("dashboard:export")
    public ResponseEntity<Resource> exportTopTags(
            @RequestParam(defaultValue = "10") int limit,
            @RequestParam(defaultValue = "excel") String format) {
        
        Resource resource = dashboardService.exportTopTags(limit, format);
        String filename = String.format("top_tags_%d.%s", limit, getFileExtension(format));

        return ResponseEntity.ok()
            .contentType(getMediaType(format))
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
            .body(resource);
    }

    private MediaType getMediaType(String format) {
        return switch (format.toLowerCase()) {
            case "excel" -> MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            case "csv" -> MediaType.parseMediaType("text/csv;charset=UTF-8");
            case "json" -> MediaType.APPLICATION_JSON;
            default -> throw new IllegalArgumentException("不支持的导出格式：" + format);
        };
    }

    private String getFileExtension(String format) {
        return switch (format.toLowerCase()) {
            case "excel" -> "xlsx";
            case "csv" -> "csv";
            case "json" -> "json";
            default -> throw new IllegalArgumentException("不支持的导出格式：" + format);
        };
    }
} 